import TCategory from '../../entry/TCategory'
import {isEmpty} from "../../../js/commonUtils";
import showroomData from "../../../stands/showroomSelect/js/showroomData";
import commonData from "../../../stands/js/stand/common_data"
/**
 * Created by shidaiapp on 2017/10/16.
 */
export const webList = (self, tiyData) => {
  self.$Spin.show();
  self.$apiClassification.getClassificationList({'level':1})
    .then(function (data) {
      self.$Spin.hide();
      if (data.success) {
        tiyData.tParam.length = [];
        let list = data.result;
        tiyData.tData.clearAll().setLevel1List(list);
        resetSelected(tiyData,1,2,3);
      } else {
        self.$Message.error(data.errorMessage);
      }
    });
};

function changeModelLoading(self, tiyData){
  tiyData.addModal.isLoading = false;
  self.$nextTick(function () {
    tiyData.addModal.isLoading = true;
  });
}

export const init=(self,tiyData)=>{
  tiyData.tData.clearAll();
  tiyData.status.resetDeleteInfo()
  tiyData.status.resetSelectedLevel(1,2,3);
};

/**
 * 获取下一级分类
 * @param self
 * @param tiyData
 * @param parentId
 */
export const getNextClassifications = (self,tiyData,level) => {
  self.$Spin.show();
  let parentId='';
  tiyData.tData.clearLevel3();

  switch(level){
    case 2:
      tiyData.tData.clearLevel2();
      parentId = tiyData.status.selectedLevel1.id;
      break;
    case 3:
      parentId = tiyData.status.selectedLevel2.id;
      break;
    default:
      return;
  }
  self.$apiClassification.getClassificationList({
    "parentId": parentId
  }).then(function (data) {
    self.$Spin.hide();
    if (data.success) {
      tiyData.tData.setList(level,data.result);
    } else {
      self.$Message.error(data.errorMessage);
    }
  });
};

export const  add = (self, tiyData,level) => {
  tiyData.status.isAdd = true;
  tiyData.tParam.classification = new TCategory();
  tiyData.tParam.showroomSelected={
    showroomTitle:'',
      showroomId:'',
      shortLink:''
  };
  tiyData.tParam.sel = new TCategory();
  switch (level) {
    case 1:
      tiyData.tParam.classification.level = 1;
      tiyData.status.resetSelectedLevel(2,3);
      break;
    case 2:
      if(tiyData.status.selectedLevel1.state===0){
        self.$Message.error('请选择父级分类!');
        return;
      }
      tiyData.tParam.classification.level=2;
      tiyData.tParam.classification.parentId = tiyData.status.selectedLevel1.id;
      tiyData.tParam.classification.isPlaceholder = tiyData.status.selectedLevel1.isPlaceholder;
      tiyData.tParam.classification.type = tiyData.status.selectedLevel1.type;
      tiyData.status.resetSelectedLevel(3);
      break;
    case 3:
      if(tiyData.status.selectedLevel2.state===0){
        self.$Message.error('请选择父级分类!');
        return;
      }
      tiyData.tParam.classification.level=3;
      tiyData.tParam.classification.parentId =tiyData.status.selectedLevel2.id;
      tiyData.tParam.classification.isPlaceholder = tiyData.status.selectedLevel2.isPlaceholder;
      tiyData.tParam.classification.type = tiyData.status.selectedLevel2.type;
      break;
    default:
      self.$Message.error('分类层级错误!');
      return;
      break;
  }

  tiyData.addModal.isShow=true;
  self.pageMetaInfo.title='';
  self.pageMetaInfo.description='';
  self.pageMetaInfo.keywords='';
  tiyData.tParam.classification.detailDesc = "";
  tiyData.addModal.title="新增"+level+"级分类"
};

export const move = (tiyData, index,level) => {
  let classification1;
  tiyData.tParam.moveCategory.parentList.length = 0;
  if(level==2){
    classification1= tiyData.tData.secondClassificationList[index];
    tiyData.tData.classificationList.forEach(function (item) {
      tiyData.tParam.moveCategory.parentList.push(item);
    });
  }else if(level=3){
    classification1= tiyData.tData.thirdClassificationList[index];
    tiyData.tData.secondClassificationList.forEach(function (item) {
      tiyData.tParam.moveCategory.parentList.push(item);
    });
  }
  tiyData.tParam.moveCategory.classification = classification1;
  tiyData.tParam.moveCategory.selectParentClassificationId = "";
  tiyData.status.modalMove.isShow = true;
  tiyData.status.modalMove.title = "迁移分类"
};

export const edit = (self, tiyData, id) => {
  tiyData.addModal.title="修改分类";
  tiyData.status.isAdd = false;
  self.$Spin.show();
  tiyData.addModal.isShow=true;
  self.$apiClassification.getClassification({'id':id})
    .then(function (data) {
      self.$Spin.hide();
      if (data.success) {
        tiyData.tParam.classification = data.result;
        tiyData.addModal.classificationState = tiyData.tParam.classification.state;
        tiyData.tParam.showroomSelected={
          showroomTitle:'',
          showroomId:'',
          shortLink:''
        };
        if(data.result.type==2&&data.result.showRoomId!=null&&data.result.showRoomId!='' ){
          tiyData.tParam.showroomSelected.showroomId = data.result.showRoomId;
          tiyData.tParam.showroomSelected.shortLink = data.result.shortLinkUrl;
        }
        //分类元数据
        self.pageMetaInfo.title='';
        self.pageMetaInfo.description='';
        self.pageMetaInfo.keywords='';
        tiyData.tParam.classification.pageMetaInfo.forEach(function(item){
          if(item.name=='title'){
            self.pageMetaInfo.title=item.value;
          }else if(item.name=='description'){
            self.pageMetaInfo.description=item.value;
          }else if(item.name=='keywords'){
            self.pageMetaInfo.keywords=item.value;
          }
        })
      } else {
        self.$Message.error(data.errorMessage);
      }
    });
};

export const actionDelete= (self,tiyData) => {
    self.$Spin.show();
    self.$apiClassification.deleteClassification({
      'id':tiyData.status.deleteId,
      "level":tiyData.status.deleteLevel,
      "name":tiyData.status.deleteName})
    .then(function (data) {
      self.$Spin.hide();
      if (data.success) {
        self.$Message.success('删除成功!');
        if(tiyData.status.deleteLevel==1){
          webList(self,tiyData);
          tiyData.status.selectedLevel1.index=-1;
          tiyData.status.selectedLevel2.index=-1;
          tiyData.status.selectedLevel3.index=-1;
        }else if(tiyData.status.deleteLevel==2){
          getNextClassifications(self,tiyData,2);
          tiyData.status.selectedLevel2.index=-1;
          tiyData.status.selectedLevel3.index=-1;
        }else{
          getNextClassifications(self,tiyData,3);
          tiyData.status.selectedLevel3.index=-1;
        }
      } else {
        self.$Message.error(data.errorMessage);
      }
    });

};

export const classificationWebAddOrModify = (self, tiyData, name) => {
  tiyData.addModal.isLoading = true;
  self.$refs[name].validate((valid) => {
    if (valid) {
      if(tiyData.tParam.classification.shortLinkName.indexOf("wholesale/")>=0){
        self.$Modal.warning({
          title: "警告",
          content: '固定网址不能包含"wholesale/"!'
        });
        return;
      }

      if(tiyData.tParam.classification.state === 0) { //启用状态
        if(isEmpty(tiyData.tParam.classification.icon) && !tiyData.tParam.classification.isPlaceholder) { //没有上传图标时分类不能启用
          self.$Modal.warning({
            title: "警告",
            content: "没有PC端分类图时分类不能启用！"
          });
          return;
        }
        if(isEmpty(tiyData.tParam.classification.shortLinkName)&&tiyData.tParam.classification.type==1){ //没有短链接名时分类不能启用
          self.$Modal.warning({
            title: "警告",
            content: "没有短链接时分类不能启用！"
          });
          return;
        }
        if(isEmpty(tiyData.tParam.showroomSelected.showroomId)&&tiyData.tParam.classification.type==2){ //没有关联展厅不能启用聚合分类
          self.$Modal.warning({
            title: "警告",
            content: "没有关联展厅不能启用分类！"
          });
          return;
        }

      }

      tiyData.tParam.classification.pageMetaInfo.splice(0,tiyData.tParam.classification.pageMetaInfo.length);
      if(self.pageMetaInfo.title!=''){
        tiyData.tParam.classification.pageMetaInfo.push({name:'title',value:self.pageMetaInfo.title})
      }
      if(self.pageMetaInfo.description!=''){
        tiyData.tParam.classification.pageMetaInfo.push({name:'description',value:self.pageMetaInfo.description})
      }
      if(self.pageMetaInfo.keywords!=''){
        tiyData.tParam.classification.pageMetaInfo.push({name:'keywords',value:self.pageMetaInfo.keywords})
      }
      let validRecommend = validRecommends(tiyData.tParam.classification.recommends);

      if(validRecommend) {
        //新增
        if(tiyData.status.isAdd) {
          saveOrUpdateClassification(self, tiyData);
        }else{//修改
          if(tiyData.tParam.classification.state != tiyData.addModal.classificationState) {
            if(tiyData.tParam.classification.state === 0) { //启用
              //查询对应展厅的子展厅是否有未上线展厅
              let params = {id: tiyData.tParam.classification.id, state: tiyData.tParam.classification.state};
              self.$Spin.show();
              self.$apiClassification.queryChildShowrooms(params).then(response => {
                self.$Spin.hide();
                if(response.success) {
                  if(response.result.length > 0) {
                    self.$Modal.confirm({
                      title: "确认",
                      content: "该分类对应的展厅的展位关联了其他未发布展厅，要先删除相关展位，然后将该分类启用吗？",
                      onOk() {
                        saveOrUpdateClassification(self, tiyData);
                      },
                    });
                  }else{
                    saveOrUpdateClassification(self, tiyData);
                  }
                }else{
                  self.$Message.error(response.errorMessage);
                }
              })
            }else{ //禁用
              //查询对应展厅的父展厅是否有已发布展厅
              let params = {id: tiyData.tParam.classification.id, state: tiyData.tParam.classification.state};
              self.$Spin.show();
              self.$apiClassification.queryParentShowrooms(params).then(response => {
                self.$Spin.hide();
                if(response.success) {
                  if(response.result.length > 0) {
                    self.$Modal.confirm({
                      title: "确认",
                      content: "该分类对应的展厅被其他已发布展厅的展位引用，要先删除相关展位，然后将该分类禁用吗？",
                      onOk() {
                        saveOrUpdateClassification(self, tiyData);
                      },
                    });
                  }else{
                    saveOrUpdateClassification(self, tiyData);
                  }
                }else{
                  self.$Message.error(response.errorMessage);
                }
              });
            }
          }else{
            saveOrUpdateClassification(self, tiyData);
          }
        }
      } else {
        self.$Modal.error({content:"关联推荐的名称和url不能为空。"});
        changeModelLoading(self, tiyData);
      }
    } else {
      changeModelLoading(self,tiyData);
    }
  });
};

function saveOrUpdateClassification(self, tiyData) {
  self.$Spin.show();
  self.$apiClassification.addEditClassification(tiyData.tParam.classification).then(function (data) {
    self.$Spin.hide();
    if (data.success) {
      tiyData.addModal.isShow = false;
      self.$Message.success('保存成功!');
      if(tiyData.tParam.classification.level==1){
        webList(self, tiyData);
      }else{
        getNextClassifications(self,tiyData,tiyData.tParam.classification.level);
        if(tiyData.tParam.classification.level==2){
          resetSelected(tiyData,2,3);
        }else{
          resetSelected(tiyData,3);
        }
      }
    } else {
      tiyData.addModal.isLoading = false;
      self.$Message.error(data.errorMessage);
    }
  });
}

function validRecommends(recommends){
  let validRecommend = true;
  if(recommends){
    for(let i = 0; i < recommends.length; i++) {
      let recommend = recommends[i];
      recommend.sequence = i;
      if(!recommend.name || !recommend.url){
        validRecommend = false;
      }
    }
  }
  return validRecommend;
}

export const deleteClassification= (tiyData) => {
  let title = '确认删除';
  let content = '确认删除该分类以及子分类';
  tiyData.status.showDeleteSureModal(title,content);
};

export const resetSelected= (tiyData,...levels) => {
  tiyData.status.resetSelectedLevel(levels)
};

/**
 * 保存需要排序的数据
 * @param self
 * @param tiyData
 */
export const webSortDoing = (self, tiyData) => {
  tiyData.status.modalSort.isLoading = true;
  self.$Spin.show();
  let sortStr = JSON.stringify(tiyData.tData.sortData.sortList);
  self.$apiClassification.sortClassification({
    "sortDatas": sortStr,
    "sortName":tiyData.tData.sortData.sortName
  }).then(function (response) {
    if (response.success) {
      self.$Message.info("保存成功!");
      self.$Spin.hide();
      tiyData.status.modalSort.hideSortModal();
      if (tiyData.tData.sortData.sortLevel == 1){
        webList(self,tiyData);
      }else {
        getNextClassifications(self, tiyData,tiyData.tData.sortData.sortLevel);
      }
    } else {
      self.$Message.error(response.errorMessage);
      self.$Spin.hide();
    }
  });
};

/**
 * 保存需要排序的数据
 * @param self
 * @param tiyData
 */
export const webMoveDoing = (self, tiyData) => {
  tiyData.status.showDeleteModal();
  self.$Spin.show();
  let moveCategory = tiyData.tParam.moveCategory;
  let level = moveCategory.classification.level;

  self.$apiClassification.moveClassifications({
    "moveClassificationId": moveCategory.classification.id,
    "moveClassificationName": moveCategory.classification.name,
    "moveClassificationLevel": level,
    "parentClassificationId": moveCategory.selectParentClassificationId,
  }).then(function (response) {
    self.$Spin.hide();
    tiyData.status.hideDeleteModal();
    if (response.success) {
      self.$Message.info("保存成功!");
      tiyData.status.resetSelectedLevel(level);
      getNextClassifications(self, tiyData, level);
    } else {
      self.$Message.error(response.errorMessage);
    }
  });
};


export const queryShowroomList = (self) => {
  let params = showroomData.tParam;
  params.pageNum = showroomData.tPage.pageNum;
  params.pageSize = showroomData.tPage.pageSize;
  params.type=commonData.standsDic.commonType;
  params.state=commonData.standsDic.states[1].value;
  self.$ySpliceAll(showroomData.tData.list);
  self.$Spin.show();
  self.$apiStand.queryStandsList(params).then(response => {
    if(response.success) {
      let page = response.result;
      showroomData.tData.list.push(...page.list);
      showroomData.tPage.total = page.total;
    }else{
      showroomData.tPage.total = 0;
      self.$Message.error(response.errorMessage);
    }
    self.$Spin.hide();
  });
};
/**修改关联展厅*/
export const modifyShowroom = (self,tiyData) => {
  if(showroomData.tData.selectedList.length == 0) {
    self.$Message.error("请选择展厅！");
    return;
  };
  tiyData.tParam.showroomSelected.showroomId=showroomData.tData.selectedList[0].id;
  tiyData.tParam.showroomSelected.title=showroomData.tData.selectedList[0].title;
  tiyData.tParam.showroomSelected.shortLink=showroomData.tData.selectedList[0].shortLink;
  tiyData.tParam.classification.showRoomId = showroomData.tData.selectedList[0].id;
  self.status.modalShowroom.isShow = false;

  // let params = tiyData.tParam.editParam.showroom;
  // self.$Spin.show();
  // self.$apiStand.updateShowroomOfBoothItem(params).then(response => {
  //   if(response.success) {
  //     self.$Message.success("关联展厅成功！");
  //     //关闭弹窗
  //     tiyData.tStatus.boothItem.modalShowroom.isShow = false;
  //     //刷新展厅信息和展位列表
  //     refreshStandsAndBoothItems(self);
  //   }else{
  //     self.$Message.error(response.errorMessage);
  //   }
  //   self.$Spin.hide();
  // });
}

